package com.ozo.easy.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.ozo.easy.common.auth.LoginUser;
import com.ozo.easy.common.auth.UserLoginHelper;
import com.ozo.easy.common.exception.ServiceException;
import com.ozo.easy.common.log.annotation.LogAnno;
import com.ozo.easy.common.model.ResultVO;
import com.ozo.easy.entity.SysUser;
import com.ozo.easy.exception.ServiceExceptionEnum;
import com.ozo.easy.pojo.dto.*;
import com.ozo.easy.service.ISysUserService;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;

/**
 * 认证控制器
 *
 * @author ozo
 * @date 2024-12-20
 */
@Tag(name = "认证管理")
@RequiredArgsConstructor
@RequestMapping("/auth")
@RestController
public class AuthController {

    private final ISysUserService sysUserService;

    @SaIgnore
    @Operation(summary = "验证码")
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        GifCaptcha gifCaptcha = new GifCaptcha(80, 38);
        gifCaptcha.setLen(4);
        // 仅数字
        gifCaptcha.setCharType(2);
        CaptchaUtil.out(gifCaptcha, request, response);
    }

    @LogAnno(value = "登录", module = "认证")
    @SaIgnore
    @Operation(summary = "登录")
    @PostMapping("/login")
    public ResultVO<Void> login(@RequestBody @Valid LoginDTO loginDTO, HttpServletRequest request) {
        if (!CaptchaUtil.ver(loginDTO.getCaptcha(), request)) {
            CaptchaUtil.clear(request);
            throw new ServiceException(ServiceExceptionEnum.CAPTCHA_NOT_RIGHT);
        }

        // 用户名不存在
        SysUser sysUser = sysUserService.getByUsername(loginDTO.getUsername());
        if (sysUser == null) {
            throw new ServiceException(ServiceExceptionEnum.USERNAME_OR_PASSWORD_NOT_RIGHT);
        }
        // 密码错误
        if (!SecureUtil.md5(loginDTO.getPassword()).equals(sysUser.getPassword())) {
            throw new ServiceException(ServiceExceptionEnum.USERNAME_OR_PASSWORD_NOT_RIGHT);
        }

        // 登录
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(sysUser.getId());
        loginUser.setUsername(sysUser.getUsername());
        loginUser.setMobile(sysUser.getMobile());
        loginUser.setNickname(sysUser.getNickname());
        loginUser.setGender(sysUser.getGender());
        loginUser.setAvatar(sysUser.getAvatar());
        loginUser.setRememberMe(loginDTO.getRememberMe());
        UserLoginHelper.login(loginUser, null);

        return ResultVO.success();
    }

    @LogAnno(value = "注册", module = "认证")
    @SaIgnore
    @Operation(summary = "注册")
    @PostMapping("/register")
    public ResultVO<Void> register(@RequestBody @Valid RegisterDTO registerDTO) {
        if (!registerDTO.getPassword().equals(registerDTO.getPasswordConfirm())) {
            throw new ServiceException(ServiceExceptionEnum.TWO_PASSWORD_NOT_MATCH);
        }

        SysUserSaveDTO saveDTO = new SysUserSaveDTO();
        saveDTO.setUsername(registerDTO.getUsername());
        saveDTO.setPassword(SecureUtil.md5(registerDTO.getPassword()));
        saveDTO.setGender("1");
        saveDTO.setNickname("默认用户");
        sysUserService.add(saveDTO);
        return ResultVO.success();
    }

    @LogAnno(value = "退出登录", module = "认证")
    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public ResultVO<Void> logout() {
        UserLoginHelper.logout();
        return ResultVO.success();
    }

    @Operation(summary = "修改密码页")
    @GetMapping({"/updatePwdForm"})
    public ModelAndView updatePwdForm() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("updatePwd");
        return modelAndView;
    }

    @Operation(summary = "修改密码")
    @PostMapping({"/updatePwd"})
    public ResultVO<Void> updatePwd(@RequestBody @Valid UpdatePwdDTO updatePwdDTO) {
        Long userId = UserLoginHelper.getUserId();
        SysUser sysUser = sysUserService.getById(userId);

        if (!updatePwdDTO.getPassword().equals(updatePwdDTO.getPasswordConfirm())) {
            throw new ServiceException(ServiceExceptionEnum.TWO_PASSWORD_NOT_MATCH);
        }

        String oldPassword = updatePwdDTO.getOldPassword();
        if (!SecureUtil.md5(oldPassword).equals(sysUser.getPassword())) {
            throw new ServiceException(ServiceExceptionEnum.OLD_PASSWORD_NOT_RIGHT);
        }
        sysUser.setPassword(SecureUtil.md5(updatePwdDTO.getPassword()));
        sysUserService.updateById(sysUser);
        return ResultVO.success();
    }

    @Operation(summary = "修改个人信息页")
    @GetMapping({"/updateInfoForm"})
    public ModelAndView updateInfoForm() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("data", sysUserService.detail(UserLoginHelper.getUserId()));
        modelAndView.setViewName("updateInfo");
        return modelAndView;
    }

    @Operation(summary = "修改个人信息")
    @PostMapping({"/updateInfo"})
    public ResultVO<Void> updateInfo(@RequestBody @Valid UpdateInfoDTO updateInfoDTO) {
        SysUserSaveDTO saveDTO = BeanUtil.copyProperties(updateInfoDTO, SysUserSaveDTO.class);
        saveDTO.setId(UserLoginHelper.getUserId());
        sysUserService.edit(saveDTO);
        return ResultVO.success();
    }

}
